<?php

class Threads extends CI_Controller {

    function __Construct() {
        parent::__Construct();
        $this->load->database();
        $this->load->helper('url', 'form');
    }

    function index() {
        redirect('threads/allthreads');
    }

    //start for thread management
    function allthreads() {
        $this->load->model('threads_mgr');
        $this->load->library('pagination');
        $this->session->set_userdata('count_threads', $this->db->count_all('tbl_threads'));

        $config['base_url'] = site_url('admin/allthread');
        $config['total_rows'] = $this->db->count_all('tbl_threads');
        
        $config['per_page'] = 10;
        $config["uri_segment"] = 3;
        $page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
        $this->pagination->initialize($config);

        $data['pages'] = $this->pagination->create_links();
        $data['title'] = 'All Threads';
        $data['forum_threads'] = $this->threads_mgr->allthread($config['per_page'], $page);

        $this->load->view('admin/allthreads', $data);
    }

    //add new thread
    function add_new() {
        $this->load->model('threads_mgr');
        $this->load->library("form_validation");

        $this->form_validation->set_rules('th_title', 'Title', 'trim|required');
        $this->form_validation->set_rules('th_content', 'Content', 'trim|required');

        if ($this->form_validation->run() == FALSE) {
            //hasn't been run or there are validation errors
            $data['title'] = 'Add Thread';
            $this->load->view('admin/add_new', $data);
        } else {
            $result['reg'] = $this->threads_mgr->addnewthread();

            if ($result) {
                redirect('threads/allthreads');
            } else {
                echo 'error';
            }
        }
    }

    //delete thread
    function delete_thread() {
        $this->load->model('threads_mgr');
        $id = $this->uri->segment(3);
        if ((int) $id > 0) {
            $oldrow = array('thread_id' => $id);
            $this->threads_mgr->deletethread($oldrow);

            redirect('threads/allthreads');
        }
    }

    //edit function by Miss. Sambo
    function select_edit_thread() {
        $this->load->model('threads_mgr');
        $data['thread_edit'] = $this->threads_mgr->thread_select_edit();
        $data['title'] = 'Update thread';

        $this->load->view('admin/select_edit_thread', $data);
    }

    //Update thread here
    function update_thread() {
        $this->load->model('threads_mgr');
        $data['thread'] = $this->threads_mgr->update_thread();
        if ($data['thread'] > 0) {
            redirect('threads/allthreads');
        }
    }

}

?>